﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using WF = CPPEI.WorkflowCore;

namespace Demo.AUDITANDREJECTWITHACTORS
{
    public partial class SelectActor : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                Guid instanceId = new Guid(Request.QueryString["wf:instance"]);
                Guid stateId = new Guid(Request.QueryString["wf:state"]);
                string action = Request.QueryString["wf:action"];
                
                WF.Instance instance = WF.Engine.Get(instanceId);
                if (instance != null)
                {
                    if(instance.State.Id != stateId)
                    {

                    }
                    else
                    {
                        for(int index = 0; index < instance.State.Activity.Next.Count; index++)
                        {
                            WF.Link next = instance.State.Activity.Next[index];
                            if(string.Equals(next.Action.Code, action))
                            {
                                for (int iActor = 0; iActor < next.To.Actors.Count; iActor++)
                                {
                                    this._ctlDDLActor.Items.Add(new ListItem(next.To.Actors[iActor].Name,
                                        next.To.Actors[iActor].Id));
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }

        protected void _ctlBtnSubmit_Click(object sender, EventArgs e)
        {
            Guid instanceId = new Guid(Request.QueryString["wf:instance"]);
            Guid stateId = new Guid(Request.QueryString["wf:state"]);
            string action = Request.QueryString["wf:action"];
            ListItem selItem = this._ctlDDLActor.SelectedItem;

            WF.Instance inst = WF.Engine.InstanceStorage.Find(instanceId);

            WF.Instance instance = WF.Engine.Run(instanceId,
                stateId,
                action,
                inst.State.Actors[0],
                new WF.Actor(selItem.Value, selItem.Text, WF.ActorType.User));

            string targetUrl = string.Format("{0}?wf:instance={1}", instance.State.Activity.Property.Page.Address, instance.Id);

            Response.Redirect(targetUrl);
        }
    }
}